package com.cj.pj.sys.service.impl;

import com.cj.pj.sys.common.annotation.AddLogs;
import com.cj.pj.sys.common.exception.ServiceException;
import com.cj.pj.sys.common.pojo.PageObject;
import com.cj.pj.sys.dao.SysRoleDao;
import com.cj.pj.sys.pojo.SysRole;
import com.cj.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    SysRoleDao sysRoleDao;

    @Override
    @AddLogs("查询角色")
    public PageObject<SysRole> findPageObject(String name, Integer pageCurrent) {
        int rowCount=sysRoleDao.findRowCount(name);
        if (rowCount==0)throw new ServiceException("没有查到结果");
        int pageSize=5;
        int startIndex=(pageCurrent-1)*pageSize;
       return new PageObject<SysRole>(pageCurrent, sysRoleDao.findPageObject(name,startIndex,pageSize),rowCount);
    }

    @Override
    @AddLogs("添加角色")
    public String addSysRole(SysRole sysRole, int... menuIds) {
        if(menuIds==null||menuIds.length==0)throw new ServiceException("没有选择功能");
        Date now=new Date();
        sysRole.setCreatedTime(now);
        sysRole.setModifiedTime(now);
        sysRoleDao.addRole(sysRole);
        sysRoleDao.addRoleMenus(sysRole.getId(),menuIds);
        return "添加角色成功";
    }

    @Override
    @AddLogs("删除角色")
    public SysRole findObjectById(int id) {
        SysRole sysRole=sysRoleDao.findObjectById(id);
        if(sysRole==null)throw new ServiceException("没有找到对应内容，所选值或许已经被删除");
        return sysRole;
    }

    @Override
    public String deleteObjectById(int id) {
        sysRoleDao.deleteRoleMenus(id);
        sysRoleDao.deleteRole(id);
        return "删除成功";
    }

    @Override
    public String updateRole(SysRole sysRole, int... methodIds) {
        sysRole.setModifiedTime(new Date());
        sysRoleDao.deleteRoleMenus(sysRole.getId());
        sysRoleDao.addRoleMenus(sysRole.getId(),methodIds);
        sysRoleDao.updataRole(sysRole);
        return "更新成功";
    }

    @Override
    public List<SysRole> findRoles() {
        return sysRoleDao.findRoles();
    }

}
